package handler

import (
	"encoding/json"
	"strconv"
	"time"
	"travel-mate/cache"
	"travel-mate/models"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	info := c.PostForm("info")
	data := models.Travel{
		Model: gorm.Model{},
		Title: title,
		Info:  info,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "add_" + strconv.Itoa(int(data.ID))
	var travel models.Travel
	models.DB.Where("id=?", data.ID).First(&travel)
	jsonData, _ := json.Marshal(travel)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*1)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	var travel []models.Travel
	redis_key := "list"
	cacheCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheCount == "" {
		models.DB.Model(&models.Travel{}).Find(&travel)
		jsonData, _ := json.Marshal(travel)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheCount), &travel)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": travel,
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")
	err := models.DB.Where("id=?", id).Delete(&models.Travel{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "add_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
